package com.maya.medicalwastes;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.inputmethodservice.ExtractEditText;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.print.sdk.PrinterConstants;
import com.android.print.sdk.PrinterInstance;
import com.maya.medicalwastes.adapter.CollectListAdapter;
import com.maya.medicalwastes.bean.QueryInfoBean;
import com.maya.medicalwastes.dialog.SureCollectDialog;
import com.maya.medicalwastes.entity.CheckIsShowValuationEntity;
import com.maya.medicalwastes.entity.CollectBean;
import com.maya.medicalwastes.entity.KeyBean;
import com.maya.medicalwastes.httpNet.ApiService;
import com.maya.medicalwastes.httpNet.HttpService;
import com.maya.medicalwastes.httpNet.callback.ResponseCallBack;
import com.maya.medicalwastes.httpNet.common.SharedPreferencesConstant;
import com.maya.medicalwastes.httpNet.manage.RetrofitManager;
import com.maya.medicalwastes.httpNet.model.ResultModel;
import com.maya.medicalwastes.print.BluetoothOperation;
import com.maya.medicalwastes.print.IPrinterOpertion;
import com.maya.medicalwastes.print.MainActivity;
import com.maya.medicalwastes.print.PrintUtils;
import com.maya.medicalwastes.ui.WarehouseActivity;
import com.maya.medicalwastes.util.CustomProber;
import com.maya.medicalwastes.util.FormatUtilA;
import com.maya.medicalwastes.util.HexDump;
import com.maya.medicalwastes.util.MyUtils;
import com.maya.medicalwastes.util.PermissionsChecker;
import com.maya.medicalwastes.util.PrefUtils;
import com.maya.medicalwastes.util.ToastUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import timing.ukulele.serialport.BuildConfig;
import timing.ukulele.serialport.driver.UsbSerialDriver;
import timing.ukulele.serialport.driver.UsbSerialPort;
import timing.ukulele.serialport.driver.UsbSerialProber;
import timing.ukulele.serialport.util.SerialInputOutputManager;

/**
 * @author created by fuguoyong
 * 版本：1.0
 * 创建日期：2020-11-19 15
 * 描述：CollectActivity
 */
public class CollectActivity extends AppCompatActivity implements SerialInputOutputManager.Listener {
    @BindView(R.id.tv_dept)
    TextView tv_dept;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.et_scan_numb)
    ExtractEditText et_scan_numb;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_waste_type)
    TextView tv_waste_type;
    @BindView(R.id.tv_weight)
    TextView tv_weight;
    @BindView(R.id.tv_wight)
    TextView tv_wight;
    @BindView(R.id.tv_list_size)
    TextView tv_list_size;
    @BindView(R.id.btn_add)
    Button btn_add;
    @BindView(R.id.btn_resize)
    Button btn_resize;
    @BindView(R.id.btn_sure)
    Button btn_sure;
    private String id;
    Double zhong = 0.0;
    private String scanStr;
    private String dept;
    private String userName;
    private CollectListAdapter adapter;
    private List<CollectBean> wasteList = new ArrayList<>();
    private CollectBean listbean;
    TelephonyManager telephonyManager;
    String imei;
    String[] str;
    private int deviceId, portNum, baudRate;
    private boolean withIoManager;

    private static boolean isConnected;
    private IPrinterOpertion myOpertion;
    private PrinterInstance mPrinter;

    private enum UsbPermission {Unknown, Requested, Granted, Denied}
    private static final String INTENT_ACTION_GRANT_USB = BuildConfig.APPLICATION_ID + ".GRANT_USB";
    private static final int READ_WAIT_MILLIS = 2000;
    private BroadcastReceiver broadcastReceiver;
    private UsbPermission usbPermission = UsbPermission.Unknown;
    private SerialInputOutputManager usbIoManager;
    private UsbSerialPort usbSerialPort;
    private boolean connected = false;
    private Handler mainLooper;
    //重量
    private String numb = "";

    public boolean flag;
    public static final int CONNECT_DEVICE = 1;
    public static final int ENABLE_BT = 2;
    private ProgressDialog dialog;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PrinterConstants.Connect.SUCCESS:
                    isConnected = true;
                    mPrinter = myOpertion.getPrinter();
                    PrintUtils.printText(getResources(), mPrinter);
                    myOpertion.close();
                    myOpertion = null;
                    mPrinter = null;
                    mainLooper.post(CollectActivity.this::connect);
                    break;
                case PrinterConstants.Connect.FAILED:
                    isConnected = false;
                    break;
                case PrinterConstants.Connect.CLOSED:
                    isConnected = false;
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);
        ButterKnife.bind(this);
//        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                return;
//            } else {
//                imei = telephonyManager.getDeviceId();
//            }
//        }
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(INTENT_ACTION_GRANT_USB)) {
                    usbPermission = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                              ? UsbPermission.Granted : UsbPermission.Denied;
                    connect();
                }
            }
        };
        mainLooper = new Handler(Looper.getMainLooper());

        //两个日历权限和一个数据读写权限
        String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//        PermissionsUtils.showSystemSetting = false;//是否支持显示系统设置权限设置窗口跳转
        //这里的this不是上下文，是Activity对象！
        PermissionsChecker.getInstance().chekPermissions(this, permissions, permissionsResult);
        initView();
        initChen();

        initClick();

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, new IntentFilter(INTENT_ACTION_GRANT_USB));
        if (usbPermission == UsbPermission.Unknown || usbPermission == UsbPermission.Granted)
            mainLooper.post(this::connect);
    }

    private void initChen() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            id = bundle.getString("ID", "");
            dept = bundle.getString("dept", "");
            userName = bundle.getString("userName", "");
            deviceId = bundle.getInt("device");
            portNum = bundle.getInt("port");
            baudRate = bundle.getInt("baud");
            withIoManager = bundle.getBoolean("withIoManager");
            tv_dept.setText(dept);
            tv_username.setText(userName);
            recyclerview.setLayoutManager(new LinearLayoutManager(this));
            adapter = new CollectListAdapter(R.layout.list_waste_item, wasteList);
            recyclerview.setAdapter(adapter);
        }
    }


    //创建监听权限的接口对象
    PermissionsChecker.IPermissionsResult permissionsResult = new PermissionsChecker.IPermissionsResult() {
        @Override
        public void passPermissons() {
        }

        @Override
        public void forbitPermissons() {
//            finish();
            Toast.makeText(CollectActivity.this, "权限不通过!", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //就多一个参数this
        PermissionsChecker.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


    private void initClick() {
        et_scan_numb.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().contains("=")) {
                    if (editable.toString().trim().contains("LJD")) {
                        et_scan_numb.setEnabled(false);
                        scanStr = editable.toString().trim();
                        keySearch();
                    } else {
                        et_scan_numb.setText("");
                    }

                }
            }
        });
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(tv_dept.getText().toString()) || TextUtils.isEmpty(tv_username.getText().toString())
                          || TextUtils.isEmpty(tv_waste_type.getText().toString()) || TextUtils.isEmpty(et_scan_numb.getText().toString())) {
                    et_scan_numb.setEnabled(true);
                    ToastUtils.ViewToast(CollectActivity.this, "数据不能为空");
                } else if (Double.parseDouble(tv_weight.getText().toString()) <= 0 && tv_weight.getText().toString().contains("0")) {
                    ToastUtils.ViewToast(CollectActivity.this, "重量不能为零");
                } else {
                    if (!isConnected) {
                        myOpertion = new BluetoothOperation(CollectActivity.this, mHandler);
                        myOpertion.chooseDevice();
                    } else {
                        if (mPrinter != null) {
                            PrintUtils.printText(getResources(), mPrinter);
                        } else {
                            myOpertion = new BluetoothOperation(CollectActivity.this, mHandler);
                            myOpertion.chooseDevice();
                        }
                    }
                    wareHouse(scanStr.split("_")[1]);

                }
            }
        });
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SureCollectDialog SureCollectDialog = new SureCollectDialog(CollectActivity.this);
                SureCollectDialog.setOnBtnClickListener(new SureCollectDialog.OnBtnClickListener() {
                    @Override
                    public void onOkClick(String base,boolean flag) {
                        if (flag){
                            listbean.setCollect_sign_picture(base);
                            save();
                        }else {
                            ToastUtils.ViewToast(CollectActivity.this,"您还没有签名");
                            return;
                        }

                    }

                    @Override
                    public void onCancelClick() {

                    }
                });
                SureCollectDialog.popDialog();
            }
        });
        btn_resize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_scan_numb.setText("");
                tv_waste_type.setText("");
                et_scan_numb.setEnabled(true);

            }
        });
    }


    public void wareHouse(String code) {
        HashMap<String, Object> params;
        params = new HashMap<>();
        params.put("codeInformation", code);
        params.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        Observable<ResultModel<QueryInfoBean>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).queryQrcodeInfo(params);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<QueryInfoBean>>() {
            @Override
            public void onResponse(ResultModel<QueryInfoBean> response) {
                if (response != null && response.httpCode == 200) {
                    if (response.data.getMessage() != null) {
                        for (CollectBean collectBean : wasteList) {
                            if (collectBean.getGarbageId().equals(scanStr.split("_")[1])) {
                                et_scan_numb.setText("");
                                tv_waste_type.setText("");
                                et_scan_numb.setEnabled(true);
                                ToastUtils.ViewToast(CollectActivity.this, "该条码已存在");
                                return;
                            }
                        }
                        //判断是否扫描
                        listbean.setCollectCarId("200");
                        listbean.setCollectPersonnel(PrefUtils.getString(CollectActivity.this, SharedPreferencesConstant.TOKEN, ""));
                        listbean.setCollectHandoverPersonDepartment(dept);
                        listbean.setCollectHandoverPerson(userName);
                        listbean.setCollectPersonnelId(App.getInstance().getUserEntity().getId() + "");
                        listbean.setCollectHandoverPersonId(id);
                        listbean.setCollectPersonnel(App.getInstance().getUserEntity().getUserName());
                        listbean.setGarbageId(str[1]);
                        listbean.setWeight(tv_weight.getText().toString());
                        listbean.setBatchWeight(tv_weight.getText().toString());
                        wasteList.add(listbean);
                        adapter.replaceData(wasteList);
                        tv_list_size.setText(wasteList.size() + "件");
                        Double wei = Double.parseDouble(tv_weight.getText().toString());
                        zhong += wei;
                        tv_wight.setText( FormatUtilA.numbFormat(zhong) + "kg");
                        et_scan_numb.setText("");
                        tv_waste_type.setText("");
                        et_scan_numb.setEnabled(true);

                    } else {
                        et_scan_numb.setEnabled(true);
                        ToastUtils.ViewToast(CollectActivity.this, "该条码已存在");
                        return;
                    }
                }
            }

            @Override
            public void onFailure(int httpCode) {
                //   closeDialog();
            }
        }, this);
    }

    public void keySearch() {
//        HashMap<String, Object> param = new HashMap<>();
//        param.put("key", "CATEGORY");
//        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
//        Observable<ResultModel<ArrayList<KeyBean>>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).Keyword(param);
//        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<ArrayList<KeyBean>>>() {
//            @Override
//            public void onResponse(ResultModel<ArrayList<KeyBean>> response) {
//                if (response != null && response.httpCode == 200) {
        List<KeyBean> mWareType = App.getInstance().getWareType();
        if (mWareType.size()>0){
            str = scanStr.split("_");
            for (KeyBean d : mWareType) {
                if (d.getKey().equals(str[2])) {
                    listbean = new CollectBean();
                    listbean.setGarbageCategory(d.getKey());
                    listbean.setGarKey(d.getValue());
                    tv_waste_type.setText(d.getValue());
                }
            }
        }

//                }
//            }
//
//            @Override
//            public void onFailure(int httpCode) {
//                et_scan_numb.setText("");
//            }
//        }, this);
    }

    public void save() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("batchNumber", wasteList.size());
        param.put("batchWeight", zhong);
        param.put("data", wasteList);
        Observable<ResultModel<String>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).save(param, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<String>>() {
            @Override
            public void onResponse(ResultModel<String> response) {
                if (response != null && response.httpCode == 200) {
                    ToastUtils.ViewToast(CollectActivity.this, "上传成功");
                    tv_wight.setText("0" + "k");
                    tv_list_size.setText("0" + "件");
                    wasteList.clear();
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);

    }

    private void connect() {
        UsbDevice device = null;
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        for (UsbDevice v : usbManager.getDeviceList().values())
            if (v.getDeviceId() == deviceId)
                device = v;
        if (device == null) {
            status("connection failed: device not found");
            return;
        }
        UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
        if (driver == null) {
            driver = CustomProber.getCustomProber().probeDevice(device);
        }
        if (driver == null) {
            status("connection failed: no driver for device");
            return;
        }
        if (driver.getPorts().size() < portNum) {
            status("connection failed: not enough ports at device");
            return;
        }
        usbSerialPort = driver.getPorts().get(portNum);
        UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
        if (usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(driver.getDevice())) {
            usbPermission = UsbPermission.Requested;
            PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
            usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
            return;
        }
        if (usbConnection == null) {
            if (!usbManager.hasPermission(driver.getDevice()))
                status("connection failed: permission denied");
            else
                status("connection failed: open failed");
            return;
        }

        try {
            usbSerialPort.open(usbConnection);
            usbSerialPort.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            if (withIoManager) {
                usbIoManager = new SerialInputOutputManager(usbSerialPort, this);
                Executors.newSingleThreadExecutor().submit(usbIoManager);
            }
            status("connected");
            connected = true;
        } catch (Exception e) {
            status("connection failed: " + e.getMessage());
            disconnect();
        }
    }

    void status(String str) {
//        SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
//        spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        tv_weight.setText(spn);
        if (str.contains("connect")){
            return;
        }else {
            tv_weight.setText(str);
        }


    }

    private void disconnect() {
        connected = false;
        if (usbIoManager != null)
            usbIoManager.stop();
        usbIoManager = null;
        try {
            if (usbSerialPort != null) {
                usbSerialPort.close();
            }
        } catch (IOException ignored) {
        }
        usbSerialPort = null;
    }

    @Override
    public void onNewData(byte[] data) {
        mainLooper.post(() -> {
            receive(data);
        });
    }

    @Override
    public void onRunError(Exception e) {
        mainLooper.post(() -> {
            status("connection lost: " + e.getMessage());
            disconnect();
        });
    }

    private void initView() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("key", "MEDICAL_WASTE_WEIGHING_METHOD");
//        if (App.getInstance().getAuthOrgEntity() != null) {
//            param.put("orgId", OriginalApplication.getInstance().getAuthOrgEntity().getOrgId());
//        }
        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        param.put("orgId", PrefUtils.getString(this, "authOrgId", ""));
        Observable<ResultModel<CheckIsShowValuationEntity>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).checkIsShowValuation(param);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<CheckIsShowValuationEntity>>() {
            @Override
            public void onResponse(ResultModel<CheckIsShowValuationEntity> response) {
                if (response != null && response.httpCode == 200) {

                    //将字符串转换成jsonObject对象
                    CheckIsShowValuationEntity entity = response.data;
                    //获取对应的值
                    if (entity.getParamValue().equalsIgnoreCase("1")) {
                        //为1显示
                        flag = true;
                    } else {
                        flag = false;
                    }

                } else {
                    ToastUtils.ViewToast(CollectActivity.this, response.msg);
                }
            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, CollectActivity.this);
    }


    private void receive(byte[] data) {
//        SpannableStringBuilder spn = new SpannableStringBuilder();
        //  spn.append("receive " + data.length + " bytes\n");

        if (data.length > 0) {
            String hexString = HexDump.toHexString(data);
            String assicString = HexDump.hexToAscii(hexString);
            numb = assicString.substring(7, assicString.length() - 4);
            if (flag) {

                    tv_weight.setText(numb + "");
                }
            }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) {
                    new Thread(new Runnable() {
                        public void run() {
                            myOpertion.open(data);
                        }
                    }).start();
                }
                break;
            case ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
                    myOpertion.chooseDevice();
                } else {
                    Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
                }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myOpertion = null;
        mPrinter = null;
    }
}


//            substring=Double.parseDouble(numb);
//            }else {
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(1000);
//                            substring= Double.parseDouble(numb)-substring;
//                            mainLooper.post(() -> {
//                                tv_weight.setText(substring+"");
//                            });
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                };
//
//            }


//        }


//}
